import uuid

from django.core.cache import cache
from rest_framework.generics import GenericAPIView

from gesture_demo_server.common.result import BaseResponse, ResultCode
from .common.filter import SearchField

from .common.viewset import BaseViewSet
from .models import DbCourse, User, DbCourseVideo, UserToken, DbCourseType
from .serializers import UserSerializer, CourseSerializer, CourseVideoSerializer, UserTokenSerializer, \
    CourseTypeSerializer
import gesture_demo_server.common.tools as tools


class UserApi(GenericAPIView):
    """ 用户相关接口 """
    LOGIN_ACTION = 'login'

    REGISTER_ACTION = 'register'

    queryset = User.objects.all()
    serializer_class = UserSerializer

    def post(self, request, action=None):
        # action = request.query_params.get('action')
        if action == ('%s' % self.REGISTER_ACTION):
            return self.do_register(request)
        elif action == ('%s' % self.LOGIN_ACTION):

            return self.do_login(request)
        else:
            return BaseResponse(message='error')

    def do_register(self, request):
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return BaseResponse(data=serializer.data)
        return BaseResponse(message=serializer.errors, code=ResultCode.MSG_PARAMETER_ERROR)

    def do_login(self, request):
        password = request.data.get('password')
        username = request.data.get('username')

        try:
            user = self.queryset.get(username=username)
        except Exception as e:
            return BaseResponse(message=f'{e}')

        if not user.verify_password(password):
            return BaseResponse(message='密码错误')

        token = uuid.uuid4().hex
        # print(token, uuid.uuid4())
        cache.set(token, user.id, timeout=60 * 60)
        user_token = UserTokenSerializer(data={
            'token': token,
            'user': user
        })
        result = {}
        old_token = UserToken.objects.filter(user=user)
        if old_token.count() == 0:
            result = tools.do_verified_saving(user_token, user)
        else:
            result['data'] = user_token.to_representation(old_token.first().update(token=token))
        return BaseResponse(message='登录成功', data=result['data'])


class CourseTypeApi(BaseViewSet):
    """ 课程类型相关接口 """
    queryset = DbCourseType.objects.all()
    serializer_class = CourseTypeSerializer


class CourseApi(BaseViewSet):
    """ 课程相关接口，包括对课程的增删改查 """
    queryset = DbCourse.objects.all()
    serializer_class = CourseSerializer
    search_fields = (
        SearchField('id', lookup='iexact'),
        SearchField('type', 'id', lookup='iexact'),
        SearchField('course_title'))
    ordering_fields = ['id']


class CourseVideoApi(GenericAPIView):
    """ 课程视频相关接口 """
    queryset = DbCourseVideo.objects.all()
    serializer_class = CourseVideoSerializer

    def get(self, request, *args, **kwargs):
        rs = self.serializer_class(instance=self.queryset.all(), many=True)
        return BaseResponse(data=rs.data)

    def post(self, request):
        # 反序列化操作
        course_videos = self.serializer_class(data=request.data)
        if course_videos.is_valid():
            course_videos.save()
            return BaseResponse(message='success')
        else:
            return BaseResponse(message='%s' % course_videos.errors, code=ResultCode.MSG_PARAMETER_ERROR)
